package qtype

import (
	"github.com/gin-gonic/gin"
	"smartLearn/models"
	"smartLearn/modules/response"
	"strconv"
	"strings"
)

func GetTypeAll(c *gin.Context) {
	typeModel := models.SystemType{};
	typeList,err:=typeModel.GetAll()
	if err!=nil{
		response.ShowError(c,err.Error())
		return
	}
	var list = map[string] []models.SystemType{
		"list":typeList,
	}

	response.ShowData(c,list)
	return

}


func GetSubjectListByTypeId(c *gin.Context) {
	typeId,err:=strconv.Atoi(c.Query("id"))
	if err != nil {
		response.ShowError(c,err.Error())
		return
	}
	subjectTypeModel := models.SystemSubjectType{}

	subjectIdList,err:=subjectTypeModel.GetSubjectIdsByTypeId(typeId)
	if err != nil {
		response.ShowError(c,err.Error())
	}
	var data = make(map[string]interface{}, 0)
	data["list"]=subjectIdList
	response.ShowData(c,data)
}
func GetTypeBySubjectId(c *gin.Context) {
	subjectId,err:=strconv.Atoi(c.Query("subjectId"))
	if err != nil {
		response.ShowError(c,err.Error())
		return
	}
	typeModel := models.SystemType{};
	typeList ,err:=typeModel.GetBySubjectId(subjectId)
	if err != nil {
		response.ShowError(c,err.Error())
	}
	var data = make(map[string]interface{}, 0)
	data["list"]=typeList
	response.ShowData(c,data)
}
func Add(c *gin.Context) {
	name:=c.Query("name")
	//读取相关的学科信息
	subjectIds:=strings.Split(c.Query("subjectIds"),",")

	subjectIdsArr := make([]int, len(subjectIds))

	var err error
	for i, v := range subjectIds {
		subjectIdsArr[i], err = strconv.Atoi(v)
		if err != nil {
			continue //如果传入非数组，那么忽略
		}
	}

	systemType:=models.SystemType{}
	systemType.Name=name
	_,err=systemType.Add(subjectIdsArr)
	if err!=nil{
		response.ShowError(c,err.Error())
		return
	}
	response.ShowSuccess(c,"添加题型成功")


}

func Update(c *gin.Context) {
	//处理输入参数
	name:=c.Query("name")
	//读取相关的学科信息
	subjectIds:=strings.Split(c.Query("subjectIds"),",")
	var err error

	subjectIdsArr := make([]int, len(subjectIds))


	for i, v := range subjectIds {
		subjectIdsArr[i], err = strconv.Atoi(v)
		if err != nil {
			continue //如果传入非数组，那么忽略
		}
	}
	typeId,err:=strconv.Atoi(c.Query("id"))
	if err != nil {
		response.ShowError(c,err.Error())
		return
	}

	systemType:=models.SystemType{}
	systemType.Name=name
	systemType.Id=typeId
	_,err=systemType.Update(subjectIdsArr)
	if err!=nil{
		response.ShowError(c,err.Error())
		return
	}
	response.ShowSuccess(c,"更新题型成功")


}
func Delete(c *gin.Context) {

	typeModel := models.SystemType{};

	var err error
	typeModel.Id,err =strconv.Atoi(c.Query("id"))
	if err!=nil{
		response.ShowError(c,err.Error())
		return
	}

	err=typeModel.Delete()
	if err!=nil{
		response.ShowError(c,err.Error())
		return
	}
	response.ShowSuccess(c,"删除题型成功" )

}
